<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 局域网视频学习系统</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin: 0;
        }

        .page-actions {
            display: flex;
            gap: 10px;
        }

        .filters-bar {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .filters-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-label {
            font-size: 12px;
            color: #666;
            font-weight: 500;
        }

        .users-table-container {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .table-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0;
        }

        .table-actions {
            display: flex;
            gap: 10px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 16px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-details h4 {
            font-size: 14px;
            font-weight: 600;
            margin: 0 0 4px 0;
            color: var(--neutral-dark);
        }

        .user-details p {
            font-size: 12px;
            color: #666;
            margin: 0;
        }

        .role-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            text-align: center;
            min-width: 60px;
        }

        .role-badge.admin {
            background: rgba(26, 83, 92, 0.1);
            color: var(--admin-color);
        }

        .role-badge.teacher {
            background: rgba(78, 205, 196, 0.1);
            color: var(--teacher-color);
        }

        .role-badge.student {
            background: rgba(255, 230, 109, 0.1);
            color: #B8860B;
        }

        .status-toggle {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }

        .status-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .status-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }

        .status-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .status-slider {
            background-color: var(--success-color);
        }

        input:checked + .status-slider:before {
            transform: translateX(26px);
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-icon:hover {
            transform: translateY(-1px);
        }

        .btn-edit {
            background: var(--primary-color);
            color: white;
        }

        .btn-edit:hover {
            background: #1e5f7a;
        }

        .btn-delete {
            background: var(--error-color);
            color: white;
        }

        .btn-delete:hover {
            background: #e55a5a;
        }

        .pagination-container {
            padding: 20px;
            display: flex;
            justify-content: center;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            color: #ccc;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        @media (max-width: 768px) {
            .filters-row {
                flex-direction: column;
                align-items: stretch;
            }
            
            .page-header {
                flex-direction: column;
                gap: 15px;
                align-items: stretch;
            }
            
            .table-responsive {
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>管理员工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="users.html" class="nav-link active">
                    <i>👥</i> 用户管理
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="pending-videos.html" class="nav-link">
                    <i>📹</i> 待审核视频
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1 class="page-title">用户管理</h1>
                <div class="page-actions">
                    <button class="btn btn-admin" onclick="showAddUserModal()">
                        <i>➕</i> 新增用户
                    </button>
                    <button class="btn btn-secondary" onclick="exportUsers()">
                        <i>📊</i> 导出数据
                    </button>
                </div>
            </div>

            <!-- 筛选栏 -->
            <div class="filters-bar">
                <div class="filters-row">
                    <div class="filter-group">
                        <label class="filter-label">角色筛选</label>
                        <select id="roleFilter" class="form-control" style="width: 120px;">
                            <option value="">全部角色</option>
                            <option value="0">管理员</option>
                            <option value="1">老师</option>
                            <option value="2">学生</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">状态筛选</label>
                        <select id="statusFilter" class="form-control" style="width: 120px;">
                            <option value="">全部状态</option>
                            <option value="active">启用</option>
                            <option value="inactive">禁用</option>
                        </select>
                    </div>
                    <div class="filter-group" style="flex: 1;">
                        <label class="filter-label">搜索用户</label>
                        <div class="search-box">
                            <input type="text" id="searchInput" class="form-control" placeholder="输入用户名或姓名搜索">
                            <i class="search-icon">🔍</i>
                        </div>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">&nbsp;</label>
                        <button class="btn btn-primary" onclick="applyFilters()">筛选</button>
                    </div>
                </div>
            </div>

            <!-- 用户表格 -->
            <div class="users-table-container">
                <div class="table-header">
                    <h3 class="table-title">用户列表</h3>
                    <div class="table-actions">
                        <span class="text-muted">共 <span id="totalUsers">0</span> 个用户</span>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>用户信息</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>注册时间</th>
                                <th>最后登录时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="usersTableBody">
                            <tr>
                                <td colspan="6" class="text-center">
                                    <div class="loading">加载中...</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="pagination-container">
                    <ul class="pagination" id="pagination">
                        <!-- 分页按钮将在这里生成 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增/编辑用户模态框 -->
    <div class="modal" id="userModal">
        <div class="modal-dialog">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalTitle">新增用户</h5>
                <button type="button" class="modal-close" onclick="hideUserModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="userId" name="id">
                    
                    <div class="form-group">
                        <label class="form-label" for="username">用户名 <span class="required">*</span></label>
                        <input type="text" id="username" name="username" class="form-control" required>
                        <div class="form-text">用户名只能包含字母、数字、下划线，长度3-20位</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="name">真实姓名 <span class="required">*</span></label>
                        <input type="text" id="name" name="name" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="email">邮箱</label>
                        <input type="email" id="email" name="email" class="form-control">
                        <div class="form-text">请输入有效的邮箱地址</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="phone">手机号</label>
                        <input type="tel" id="phone" name="phone" class="form-control">
                        <div class="form-text">请输入11位手机号码</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="password">密码 <span class="required" id="passwordRequired">*</span></label>
                        <input type="password" id="password" name="password" class="form-control">
                        <div class="form-text" id="passwordHelpText">密码至少6位</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="role">角色 <span class="required">*</span></label>
                        <select id="role" name="role" class="form-control" required>
                            <option value="">请选择角色</option>
                            <option value="0">管理员</option>
                            <option value="1">老师</option>
                            <option value="2">学生</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideUserModal()">取消</button>
                <button type="button" class="btn btn-admin" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>

    <script src="../js/common.js"></script>
    <script>
        let currentUsers = [];
        let filteredUsers = [];
        let currentPage = 1;
        const pageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查权限
            if (!UserManager.hasPermission(0)) {
                Message.error('权限不足');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 2000);
                return;
            }

            // 加载用户数据
            loadUsers();
            
            // 绑定搜索事件
            document.getElementById('searchInput').addEventListener('input', 
                Utils.debounce(applyFilters, 300)
            );
        });

        // 加载用户数据
        async function loadUsers() {
            try {
                const response = await API.get('/user/all');
                if (response.success) {
                    currentUsers = response.users;
                    filteredUsers = [...currentUsers];
                    renderUsers();
                    updatePagination();
                } else {
                    Message.error('加载用户数据失败');
                }
            } catch (error) {
                console.error('加载用户失败:', error);
                Message.error('加载用户数据失败');
            }
        }

        // 渲染用户列表
        function renderUsers() {
            const tbody = document.getElementById('usersTableBody');
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageUsers = filteredUsers.slice(startIndex, endIndex);
            
            if (pageUsers.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center">
                            <div class="empty-state">
                                <i>👥</i>
                                <p>暂无用户数据</p>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }
            
            tbody.innerHTML = pageUsers.map(user => `
                <tr>
                    <td>
                        <div class="user-info">
                            <div class="user-avatar">${(user.name || user.username).charAt(0).toUpperCase()}</div>
                            <div class="user-details">
                                <h4>${user.name || user.username}</h4>
                                <p>@${user.username}</p>
                            </div>
                        </div>
                    </td>
                    <td>
                        <span class="role-badge ${getRoleClass(user.role)}">${getRoleName(user.role)}</span>
                    </td>
                    <td>
                        <label class="status-toggle">
                            <input type="checkbox" ${user.status !== 0 ? 'checked' : ''} 
                                   onchange="toggleUserStatus(${user.id}, this.checked)">
                            <span class="status-slider"></span>
                        </label>
                    </td>
                    <td>${Utils.formatTime(user.createTime)}</td>
                    <td>${user.lastLoginTime ? Utils.formatTime(user.lastLoginTime) : '从未登录'}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn-icon btn-edit" onclick="editUser(${user.id})" title="编辑">
                                ✏️
                            </button>
                            <button class="btn-icon btn-delete" onclick="deleteUser(${user.id})" title="删除">
                                🗑️
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
            
            document.getElementById('totalUsers').textContent = filteredUsers.length;
        }

        // 获取角色名称
        function getRoleName(role) {
            switch (role) {
                case 0: return '管理员';
                case 1: return '老师';
                case 2: return '学生';
                default: return '未知';
            }
        }

        // 获取角色样式类
        function getRoleClass(role) {
            switch (role) {
                case 0: return 'admin';
                case 1: return 'teacher';
                case 2: return 'student';
                default: return '';
            }
        }

        // 应用筛选
        function applyFilters() {
            const roleFilter = document.getElementById('roleFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            filteredUsers = currentUsers.filter(user => {
                // 角色筛选
                if (roleFilter && user.role.toString() !== roleFilter) {
                    return false;
                }
                
                // 状态筛选
                if (statusFilter) {
                    const isActive = user.status !== 0;
                    if (statusFilter === 'active' && !isActive) return false;
                    if (statusFilter === 'inactive' && isActive) return false;
                }
                
                // 搜索筛选
                if (searchTerm) {
                    const searchFields = [user.username, user.name].filter(Boolean);
                    if (!searchFields.some(field => field.toLowerCase().includes(searchTerm))) {
                        return false;
                    }
                }
                
                return true;
            });
            
            currentPage = 1;
            renderUsers();
            updatePagination();
        }

        // 更新分页
        function updatePagination() {
            const totalPages = Math.ceil(filteredUsers.length / pageSize);
            const pagination = document.getElementById('pagination');
            
            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }
            
            let paginationHTML = '';
            
            // 上一页
            if (currentPage > 1) {
                paginationHTML += `<li><a href="#" onclick="changePage(${currentPage - 1})">上一页</a></li>`;
            }
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                paginationHTML += `<li class="${i === currentPage ? 'active' : ''}">
                    <a href="#" onclick="changePage(${i})">${i}</a>
                </li>`;
            }
            
            // 下一页
            if (currentPage < totalPages) {
                paginationHTML += `<li><a href="#" onclick="changePage(${currentPage + 1})">下一页</a></li>`;
            }
            
            pagination.innerHTML = paginationHTML;
        }

        // 切换页面
        function changePage(page) {
            currentPage = page;
            renderUsers();
            updatePagination();
        }

        // 显示新增用户模态框
        function showAddUserModal() {
            document.getElementById('userModalTitle').textContent = '新增用户';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            
            // 新增用户时密码字段为必填
            document.getElementById('password').required = true;
            document.getElementById('passwordRequired').style.display = 'inline';
            document.getElementById('passwordHelpText').textContent = '密码至少6位';
            
            Modal.show('userModal');
        }

        // 编辑用户
        function editUser(userId) {
            const user = currentUsers.find(u => u.id === userId);
            if (!user) return;
            
            document.getElementById('userModalTitle').textContent = '编辑用户';
            document.getElementById('userId').value = user.id;
            document.getElementById('username').value = user.username;
            document.getElementById('name').value = user.name || '';
            document.getElementById('email').value = user.email || '';
            document.getElementById('phone').value = user.phone || '';
            document.getElementById('password').value = '';
            document.getElementById('role').value = user.role;
            
            // 编辑时密码字段变为可选
            document.getElementById('password').required = false;
            document.getElementById('passwordRequired').style.display = 'none';
            document.getElementById('passwordHelpText').textContent = '留空则不修改密码';
            
            Modal.show('userModal');
        }

        // 隐藏用户模态框
        function hideUserModal() {
            Modal.hide('userModal');
        }

        // 保存用户
        async function saveUser() {
            const form = document.getElementById('userForm');
            const formData = new FormData(form);
            const userId = formData.get('id');
            
            // 表单验证
            const validation = FormValidator.validate(form);
            if (!validation.isValid) {
                Message.error(validation.errors.join('<br>'));
                return;
            }
            
            try {
                if (userId) {
                    // 编辑用户 - 处理空值，密码字段可选
                    const userData = {
                        username: formData.get('username') || '',
                        name: formData.get('name') || '',
                        email: formData.get('email') || '',
                        phone: formData.get('phone') || '',
                        role: parseInt(formData.get('role')) || 2
                    };
                    
                    // 如果密码字段有值，则包含密码
                    const password = formData.get('password');
                    if (password && password.trim() !== '') {
                        userData.password = password;
                    }
                    
                    // 调试信息
                    console.log('=== Frontend Debug ===');
                    console.log('Form Data:');
                    for (let [key, value] of formData.entries()) {
                        console.log(key + ': ' + value);
                    }
                    console.log('User Data to send:', userData);
                    console.log('=== End Frontend Debug ===');
                    
                    const response = await API.put(`/user/admin/update/${userId}`, userData);
                    if (response.success) {
                        Message.success('用户更新成功');
                        hideUserModal();
                        loadUsers();
                    } else {
                        Message.error(response.message || '更新失败');
                    }
                } else {
                    // 新增用户 - 包含密码字段
                    const userData = {
                        username: formData.get('username'),
                        name: formData.get('name'),
                        email: formData.get('email'),
                        phone: formData.get('phone'),
                        password: formData.get('password'),
                        role: parseInt(formData.get('role'))
                    };
                    
                    const response = await API.post('/user/admin/create', userData);
                    if (response.success) {
                        Message.success('用户创建成功');
                        hideUserModal();
                        loadUsers();
                    } else {
                        Message.error(response.message || '创建失败');
                    }
                }
            } catch (error) {
                console.error('保存用户失败:', error);
                Message.error('操作失败：' + error.message);
            }
        }

        // 切换用户状态
        async function toggleUserStatus(userId, isActive) {
            try {
                const response = await API.put(`/user/status/${userId}`, {
                    status: isActive ? 1 : 0
                });
                
                if (response.success) {
                    // 更新本地数据
                    const user = currentUsers.find(u => u.id === userId);
                    if (user) {
                        user.status = isActive ? 1 : 0;
                    }
                    Message.success(`用户已${isActive ? '启用' : '禁用'}`);
                } else {
                    Message.error(response.message || '操作失败');
                    // 恢复checkbox状态
                    const checkbox = document.querySelector(`input[onchange="toggleUserStatus(${userId}, this.checked)"]`);
                    if (checkbox) {
                        checkbox.checked = !isActive;
                    }
                }
            } catch (error) {
                console.error('切换用户状态失败:', error);
                Message.error('操作失败');
                // 恢复checkbox状态
                const checkbox = document.querySelector(`input[onchange="toggleUserStatus(${userId}, this.checked)"]`);
                if (checkbox) {
                    checkbox.checked = !isActive;
                }
            }
        }

        // 删除用户
        function deleteUser(userId) {
            const user = currentUsers.find(u => u.id === userId);
            if (!user) return;
            
            Modal.confirm(`确认删除用户 "${user.name || user.username}" 吗？此操作不可恢复！`, async () => {
                try {
                    const response = await API.delete(`/user/admin/delete/${userId}`);
                    if (response.success) {
                        Message.success('用户删除成功');
                        loadUsers();
                    } else {
                        Message.error(response.message || '删除失败');
                    }
                } catch (error) {
                    console.error('删除用户失败:', error);
                    Message.error('删除失败：' + error.message);
                }
            });
        }

        // 导出用户数据
        function exportUsers() {
            try {
                const csvContent = generateUserCSV(filteredUsers);
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `users_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                Message.success('用户数据导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                Message.error('导出失败');
            }
        }

        // 生成用户CSV
        function generateUserCSV(users) {
            const headers = ['ID', '用户名', '姓名', '角色', '状态', '注册时间', '最后登录时间'];
            const rows = users.map(user => [
                user.id,
                user.username,
                user.name || '',
                getRoleName(user.role),
                user.status !== 0 ? '启用' : '禁用',
                Utils.formatTime(user.createTime),
                user.lastLoginTime ? Utils.formatTime(user.lastLoginTime) : '从未登录'
            ]);
            
            // 添加BOM头以支持中文显示
            return '\uFEFF' + [headers, ...rows].map(row => 
                row.map(field => `"${field}"`).join(',')
            ).join('\n');
        }
    </script>
</body>
</html>
